package cn.peach.user.controller;

import cn.peach.basic.exception.MyException;
import cn.peach.user.domain.User;
import cn.peach.user.dto.UserDto;
import cn.peach.user.query.UserQuery;
import cn.peach.user.service.IUserService;
import cn.peach.basic.util.AjaxResult;
import cn.peach.basic.util.PageList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
@Api(tags = "员工接口", description = "店铺接口详细描述")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping("/{id}")
    @ApiOperation(value = "查询一条数据", notes = "")
    public User findById(@PathVariable("id") Long id) {
        return  userService.findById(id);
    }

    @GetMapping
    @ApiOperation(value = "查询所有",notes = "")
    public List<User> findAll() {
        return userService.findAll();
    }

    @PostMapping
    @ApiOperation(value = "分页查询",notes = "")
    public PageList<User> queryPage(@RequestBody UserQuery query) {
        return userService.queryList(query);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除",notes = "传一个id")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            userService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("垃圾系统。。。");
        }
    }

    @PutMapping
    @ApiOperation(value = "店铺添加或修改",notes = "有id就是修改反之就是添加")
    public AjaxResult addAndUpdate(@RequestBody User user) {
        try {
            if (user.getId() == null){
                userService.insert(user);
            }else {
                userService.update(user);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("垃圾系统404");
        }
    }

    @PostMapping("/phone/register")
    public AjaxResult phoneRegister(@RequestBody UserDto userDto){
        try {
            // 获取前端传过来的各个参数
            userService.phoneRegister(userDto);
            return AjaxResult.me();
        } catch (MyException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setMessage("垃圾系统0^0");
        }
    }
}
